package com.gw.business.putdata.controller;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.catalina.loader.WebappClassLoader;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gw.business.common.constant.TrackBehavior;
import com.gw.business.putdata.model.UserTrackModel;
import com.gw.business.putdata.requestBody.UserReceiveRequest;
import com.gw.business.putdata.responseBody.CommonResponse;
import com.gw.platform.controller.DefaultController;
import com.gw.platform.logger.Log;

/**
 * 
 * 类功能:处理用户登录请求控制器
 * 
 *  
 * <p>创建者:Sping</p>
 * 
 * <p>创建时间:2015-02-02</p>
 * 
 * <p>修改者:</p>
 * 
 * <p>修改时间:</p>
 * 
 * <p>修改原因：</p>
 * 
 * <p>审核者:</p>
 * 
 * <p>审核时间:</p>
 * 
 * <p>审核意见：</p>
 * 
 */
@Controller
@RequestMapping("putData")
public class PutDataController extends DefaultController{
	private final static Logger logger= Logger.getLogger(DefaultController.class);
	/**
	 * 
	 * 
		<!-- 批量保存资讯 -->
			<insert id="insert" parameterType="java.util.List">
		 insert into sns_user_relation_info (user_id,attention_user_id) values
		 <foreach collection="list" item="item" index="index" separator=",">
		 (#{item.userId}, #{item.attentionUserId})
		 </--foreach>
		</--insert>
	 */
	@RequestMapping(value = "/ajax/ajaxTrackData2" ,method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public Callable<Object> demo(@RequestBody final UserReceiveRequest requestBody) {
		return new Callable<Object>() {
			public Object call() throws Exception{
				String href = "";
				String flag = "";
				String gacookiesTrack = "";
				String account_cookie_track = "";
				if (!isfreash(href)) {
					try {
						if (requestBody.getData().size()>0) {
						for (int i = 0; i < requestBody.getData().size(); i++) {
							href = requestBody.getData().get(i).getHref();
							flag = requestBody.getData().get(i).getFlag();
							gacookiesTrack =requestBody.getData().get(i).getGacookiesTrack();
							account_cookie_track = requestBody.getData().get(i).getUser_id();
						}
					}
						String regIP = request.getRemoteAddr();
						UserTrackModel track = new UserTrackModel();
						Map<String,String> map = analysisCookie(gacookiesTrack);
					/*	track.setUtmccn("(direct)".equals(map.get("utmccn"))?"":map.get("utmccn"));
						track.setUtmcct(map.get("utmcct"));
						track.setUtmcmd("(none)".equals(map.get("utmcmd"))?"":map.get("utmcmd"));
						track.setUtmcsr("(direct)".equals(map.get("utmcsr"))?"":map.get("utmcsr"));
						track.setUtmctr(map.get("utmctr"));*/
						track.setUtmccn(map.get("utmccn"));
						track.setUtmcct(map.get("utmcct"));
				        track.setUtmcmd(map.get("utmcmd"));
				        track.setUtmcsr(map.get("utmcsr"));
				        track.setUtmctr(map.get("utmcsr"));
						track.setUser_id(account_cookie_track);
						track.setIp(regIP);
						track.setVisit_time(new Date());
						track.setBrowser_count(1);
						
						if ("live".equals(flag)) {
							track.setBehavior_type(TrackBehavior.LIVE.getValue());
							track.setDemo_count(0);
							track.setReal_count(0);
							track.setVisit_count(0);
							track.setDeposit_count(0);
							track.setAdvisory_count(1);
						}else{
							track.setDemo_count(0);
							track.setReal_count(0);
							track.setDeposit_count(0);
							track.setAdvisory_count(0);
							track.setVisit_count(1);
							track.setBehavior_type(TrackBehavior.VISIT.getValue());
							
						}
						track.setUrl(href);
	
					} catch (Exception e) {
						Log.error(this.getClass(),"Forex Static AjaxGetTrackData analysisCookie:",e);
					
					}
					
				}
				return new CommonResponse();
			}
		};
	}
	
	public String getRemortIP() 
	{
		  String ip  =  request.getHeader( " x-forwarded-for " );  
	       if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {  
	          ip  =  request.getHeader( " Proxy-Client-IP " );  
	      }   
	       if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {  
	          ip  =  request.getHeader( " WL-Proxy-Client-IP " );  
	      }   
	       if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {  
	         ip  =  request.getRemoteAddr();  
	     }   
	      return  ip;  
	} 
	
	/**
	 * 装好json数据
	 */
	public List<UserTrackModel> getUserTrackModelList(String data)throws Exception{
		String ip =getRemortIP();
		//System.out.println("ip---->"+ip);
    	 JSONObject jsonobject = JSONObject.fromObject(data);
    	 JSONArray array = jsonobject.getJSONArray("data");
    	   //将json数组 转换成 List<UserTrackModel>泛型
    	 List<UserTrackModel> list = new ArrayList<UserTrackModel>();
        Map<String,String> map = null;
    	 for (int i = 0; i < array.size(); i++) {   
	         JSONObject object = (JSONObject)array.get(i);  
	         UserTrackModel passport = (UserTrackModel)JSONObject.toBean(object,
	            		UserTrackModel.class);
	       //  passport.setIp(ip);
	         passport.setBrowser_count(1);
	         if(passport != null){
		        map =  analysisCookie(passport.getGacookiesTrack());
		        passport.setUtmccn(map.get("utmccn"));
		        passport.setUtmcct(map.get("utmcct"));
		        passport.setUtmcmd(map.get("utmcmd"));
		        passport.setUtmcsr(map.get("utmcsr"));
		        String str= "";
		        if (StringUtils.isNotBlank(map.get("utmctr"))) {
                    String old = map.get("utmctr");
                    str = old;
                    if(old.equals(new String(old.getBytes("UTF-8"),"UTF-8"))){
                        str = URLDecoder.decode(map.get("utmctr"),"UTF-8");
                    }else if(old.equals(new String(old.getBytes("iso8859_1"),"iso8859_1"))){
                        str = URLDecoder.decode(map.get("utmctr"),"iso8859_1");
                        str = new String(str.getBytes("iso8859_1"),"UTF-8");
                    }else if(old.equals(new String(old.getBytes("gb2312"),"gb2312"))){
                        str = new String(str.getBytes("gb2312"),"UTF-8");
                    }
				}
		        passport.setUtmctr(str);
		        if ("live".equals(passport.getFlag())) {
		        	passport.setBehavior_type(TrackBehavior.LIVE.getValue());
		        	passport.setAdvisory_count(1);
				}else{
					passport.setVisit_count(1);
					passport.setBehavior_type(TrackBehavior.VISIT.getValue());
				}
		        if (passport.getUrl().indexOf("mobile-")!=-1 || passport.getUrl().indexOf("m.gwfx.com")!=-1 || passport.getUrl().indexOf("testm.gwfx.com")!=-1 || passport.getUrl().indexOf("nzMobileAccount-")!=-1) {
		        	passport.setPlatform_type(1);
				}else{
					passport.setPlatform_type(0);
				}
		        passport.setVisit_time(new Date());

                 if(StringUtils.isBlank(passport.getUser_id())){
                     continue;
                 }

                 if(StringUtils.isBlank(passport.getUtmcsr())){
                     passport.setUtmcsr("(direct)");
                     passport.setUtmccn("(direct)");
                 }

                 if(StringUtils.isBlank(passport.getUtmcmd())){
                     passport.setUtmcmd("(none)");
                 }
                 
                 if(StringUtils.isNotBlank(passport.getUtmcct())){
                            if (passport.getUtmcct().length()>40) {
                            	passport.setUtmcct(passport.getUtmcct().substring(0,40));
							}else{
								passport.setUtmcct(passport.getUtmcct());
							}
                 }

	            list.add(passport);
	           }  
    	    }

    	 return list;
	}
	
	/**
	 * 接收基础数据
	 */
	@RequestMapping(value="/ajax/ajaxTrackData",method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	protected  void ajaxTrackData(String data,String callback)throws Exception {
		  PrintWriter printWriter = response.getWriter();  
		  String success = "";
			
		  try {
              List<UserTrackModel> list = getUserTrackModelList(data);
	       if (list!=null && list.size()>0) {
	    	   if (!isfreash(list.get(0).getUrl()) || "live".equals(list.get(0).getFlag())) {
				
			
	    	   defaultService.insert("user_track_basic.insert", list);
				response.setStatus(200);
				success = "OK";
				response.setCharacterEncoding("utf-8");          
			    response.setContentType("text/html; charset=utf-8");    
			    printWriter.write(success); 
	    	   }
		}else{
			 success = "ERROR";
			 printWriter.write(success);    
			 Log.info(this.getClass(),"Forex Static AjaxGetTrackData size:0");
		}
			   
	
		} catch (Exception e) {
			 success = "ERROR";
			 printWriter.write(success);    
			 Log.error(this.getClass(),"Forex Static AjaxGetTrackData analysisCookie:",e);
			 e.printStackTrace();
		}
	    printWriter.flush();    
        printWriter.close();   
	}
	
	
	/**
	 * 解析cookie 参数
	 * @param gacookiesTrack
	 * @return
	 */
	private  Map<String,String> analysisCookie(String gacookiesTrack){
		Map<String,String> map=new HashMap<String,String>();
		map.put("utmcsr", "");
		map.put("utmcmd", "");
		map.put("utmccn", "");
		map.put("utmcct", "");
		map.put("utmctr", "");
	//	http://testweb.gwfx.com:8080/GwUserTrackingManager/putData/ajax/ajaxTrackData
		//utmcsr=baidu-c|utmccn=b-pp-cz-jd|utmcmd=sem|utmctr=FX4500|utmcct=waihui
		try{
			 
			if(StringUtils.isNotBlank(gacookiesTrack)){
			   String utmzStr=gacookiesTrack.substring(gacookiesTrack.indexOf("utmz"));
			   utmzStr=URLDecoder.decode(utmzStr, "UTF-8");
			   String str0=utmzStr.substring(0, utmzStr.indexOf("&"));
			   String[] arr0=str0.split("\\|");
			   String[] arr1=null;
			   String[] arr2={"utmcsr","utmcmd","utmccn","utmcct","utmctr"};
			   for(String arr0Str:arr0){
				   for(String arr2Str:arr2 ){
					   int index=arr0Str.indexOf(arr2Str);
				       if(index>0)
					     arr0Str=arr0Str.substring(index);
				   }
				   arr1=arr0Str.split("=");
				   map.put(arr1[0],arr1[1]);
			   }
			}
			
//		   LOG.info();
		   Log.info(this.getClass(),"AjaxGetTrackData analysisCookie-->map:"+map.toString());

		}
		catch(Exception e){
			Log.error(this.getClass(),"Forex Static AjaxGetTrackData analysisCookie:",e);
			//logger.error("Forex Static AjaxGetTrackData analysisCookie:",e);
		}
		return map;
   }
	/**
	 * 拦截页面录入到数据库
	 * @param url
	 * @return
	 */
	public  boolean isfreash(String url){
		boolean freash = false;
		//String[] fre = {"demoAccountSuccess.html","nzAccountSuccess.html","ukAccountSuccess.html"};
		String[] fre = {"Success.html","Sucess-2.html","ibclientperAccount","succ.html"};
		if (StringUtils.isNotBlank(url)) {
		for (int i = 0; i < fre.length; i++) {
			if (url.indexOf(fre[i])!=-1) {
				freash = true;
				break;
			}
		}
	}
		return freash;
	}
}
